import { Body, Controller, Get, Param, Put, Request } from "@nestjs/common";
import { ApiBearerAuth, ApiOperation, ApiTags } from "@nestjs/swagger";
import { Roles } from "src/utils/decorators/roles.guard";
import { JwtPayload } from "src/utils/interfaces/jwt.interface";
import { DeliveryService } from "./delivery.service";
import { UpdateDeliveryDto } from "./dto/update-delivery.dto";

@Controller("delivery")
@ApiTags("送货单")
@ApiBearerAuth()
export class DeliveryController {
  constructor(private readonly deliveryService: DeliveryService) {}

  @Get("list")
  @ApiOperation({
    summary:
      "列出所有送货单列表，如果是管理员，列出所有，如果不是，列出当前用户所在公司的所有",
  })
  list(@Request() req) {
    if (req.user.aud === "admin") {
      return this.deliveryService.findAll();
    } else {
      const companyId = req.user.company;
      return this.deliveryService.findByCompany(companyId);
    }
  }

  @Get("count")
  @ApiOperation({
    summary:
      "列出所有送货单数量，如果是管理员，列出所有，如果不是，列出当前用户所在公司的送货单数量",
  })
  count(@Request() req: { user: JwtPayload }) {
    const companyId = req.user.company;
    return this.deliveryService.count(companyId);
  }

  @Get("last")
  @ApiOperation({
    summary: "找出最后一个新增的送货单",
  })
  findLast(@Request() req: { user: JwtPayload }) {
    const companyId = req.user.company;
    return this.deliveryService.findLast(companyId);
  }

  @Get("list/:companyId")
  @Roles("admin")
  @ApiOperation({
    summary: "列出公司id对应的所有送货单列表, 只有管理员有此权限",
  })
  listByCompany(@Param("companyId") companyId: string) {
    return this.deliveryService.findByCompany(companyId);
  }

  @Get(":id")
  @ApiOperation({
    summary: "根据ID查找送货单",
  })
  find(@Param("id") id: string) {
    return this.deliveryService.find(id);
  }

  @Put(":id")
  @ApiOperation({
    summary: "根据ID更新送货单",
  })
  update(
    @Request() req: { user: JwtPayload },
    @Param("id") id: string,
    @Body() updateDeliveryDto: UpdateDeliveryDto
  ) {
    return this.deliveryService.update(updateDeliveryDto, id, req.user.sub);
  }
}
